package com.example.lottery_system.common.advice;

import com.example.lottery_system.common.pojo.CommonResult;
import com.example.lottery_system.common.utils.JacksonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;




@ControllerAdvice
@ResponseBody
public class CommonResultReturn implements ResponseBodyAdvice {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        /**
         * 讲这个设置为 true 表示需要统一结果返回
         */
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        /**
         1. 首先判断是否是CommonResult 类型
         */

        if (body instanceof CommonResult<?>) {
            return JacksonUtil.writeValueAsString(body);
        }

        /**
         2. 否则就转化成统一数据并返回
         */
        CommonResult<Object> result = CommonResult.success(body);

        /**
         3. 转化为JSON 字符串返回
         */
        return result;
//        return JacksonUtil.writeValueAsString(result);
    }
}
